@file:OptIn(ExperimentalMaterial3Api::class)

package com.ljj.bitetime.ui.activity

import android.Manifest
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.baidu.mapapi.map.MapPoi
import com.baidu.mapapi.map.MapStatus
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.search.core.SearchResult
import com.baidu.mapapi.search.geocode.GeoCodeResult
import com.baidu.mapapi.search.geocode.GeoCoder
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.ljj.bitetime.R
import com.ljj.bitetime.ui.theme.BiteTimeTheme
import kotlinx.coroutines.launch
import java.util.UUID

// 地址数据类
data class UserAddressMsg(
    val id: String = UUID.randomUUID().toString(),
    val name: String,
    val phone: String,
    val address: Address,
    val isDefault: Boolean = false
)

/**
 * 地址详情
 * @param province 省
 * @param city 市
 * @param district 区/县/县级市
 * @param street 街道/镇
 * @param addressDetail 详细地址
 */
data class Address(
    val province: String = "",
    val city: String = "",
    val district: String = "",
    val street: String = "",
    val addressDetail: String = ""
) {
    override fun toString(): String {
        return "UserAddressMsg(province='$province', city='$city', district='$district', street='$street', address='$addressDetail')"
    }
}

class AddressActivity : ComponentActivity() {
    companion object {
        private const val DEFAULTLAT = 39.9042
        private const val DEFAULTLNG = 116.4074
        private const val DEFAULTZOOM = 16.0f // 默认缩放级别：街区级
    }

    private val context = this
    private lateinit var sharedPreferences: SharedPreferences
    private val gson = Gson()
    private var mSingleLocationClient: LocationClient? = null
    private var mGeoCoder: GeoCoder? = null
    private val locationPermissionRequest = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        when {
            permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) -> {
                location()
            }
            permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false) -> {
                location()
            }
            else -> {
                Toast.makeText(this, "位置权限被拒绝，无法获取位置信息", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private var currentLatitude by mutableDoubleStateOf(0.0)
    private var currentLongitude by mutableDoubleStateOf(0.0)
    private var currentProvince by mutableStateOf("")
    private var currentCity by mutableStateOf("")
    private var currentDistrict by mutableStateOf("")
    private var currentStreet by mutableStateOf("")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        sharedPreferences = getSharedPreferences("addresses", MODE_PRIVATE)
        initBaidu()
        setContent {
            BiteTimeTheme {
                AddressScreen()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mSingleLocationClient?.stop()
        mGeoCoder?.destroy()
    }

    /* 流程方法 */
    // 初始化定位
    private fun initBaidu() {
        // 设置百度SDK隐私合规
        SDKInitializer.setAgreePrivacy(applicationContext, true)
        SDKInitializer.initialize(applicationContext)
        // 初始化定位客户端
        LocationClient.setAgreePrivacy(true)
        mSingleLocationClient = LocationClient(applicationContext)
        val option = LocationClientOption().apply {
            locationMode = LocationClientOption.LocationMode.Hight_Accuracy
            openGps = true
            coorType = "bd09ll"
            scanSpan = 0 // 设置为0表示单次定位
            isOnceLocation = true // 单次定位
            setNeedNewVersionRgc(true) // 需要最新版本逆地理编码
            setIsNeedAddress(true) // 需要地址信息
        }
        mSingleLocationClient?.locOption = option
        // 初始化GeoCoder对象
        mGeoCoder = GeoCoder.newInstance()
    }

    /* 工具方法 */
    /**
     * 执行定位操作，获取当前位置信息并更新地址信息
     * @param onComplete 定位成功并更新信息后的可选回调函数，更新Compose UI时需要置于协程域
     */
    private fun location(onComplete: (() -> Unit)? = null) {
        Log.d("BaiduLocation", "开始单次位置请求")
        if (!checkLocationPermission()) {
            Log.d("BaiduLocation", "位置权限未授予，正在请求权限")
            requestLocationPermission()
            return
        }
        val locationListener = object : BDAbstractLocationListener() {
            override fun onReceiveLocation(location: BDLocation?) {
                Log.d("BaiduLocation", "接收到位置信息: $location")
                if (location != null) {
                    Log.d("BaiduLocation", "位置类型: ${location.locType}")
                    Log.d("BaiduLocation", "纬度: ${location.latitude}, 经度: ${location.longitude}")
                    if (location.locType != BDLocation.TypeServerError) {
                        currentLatitude = location.latitude
                        currentLongitude = location.longitude
                        // 从定位结果获取地址信息
                        location.apply {
                            currentProvince = province ?: ""
                            currentCity = city ?: ""
                            currentDistrict = district ?: ""
                            currentStreet = street ?: ""
                        }
                        Log.d("BaiduLocation", "定位成功 - 省份: $currentProvince, 城市: $currentCity, 区县: $currentDistrict, 街道: $currentStreet")
                        onComplete?.invoke()
                    } else {
                        Log.e("BaiduLocation", "位置服务错误: ${location.locType}")
                        Toast.makeText(context, "定位失败，错误代码: ${location.locType}", Toast.LENGTH_SHORT).show()
                        onComplete?.invoke()
                    }
                } else {
                    Log.e("BaiduLocation", "位置信息为空")
                    Toast.makeText(context, "无法获取位置信息", Toast.LENGTH_SHORT).show()
                    onComplete?.invoke()
                }
                // 单次定位完成后停止
                mSingleLocationClient?.stop()
            }
            override fun onLocDiagnosticMessage(locType: Int, diagnosticType: Int, diagnosticMessage: String?) {
                super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage)
                Log.w("BaiduLocation", "诊断信息 - 类型: $locType, 诊断类型: $diagnosticType, 消息: $diagnosticMessage")
            }
        }
        // 重新注册监听器并启动
        mSingleLocationClient?.unRegisterLocationListener(locationListener)
        mSingleLocationClient?.registerLocationListener(locationListener)
        mSingleLocationClient?.start()
    }


    // 检查定位权限
    private fun checkLocationPermission(): Boolean {
        val fineLocationGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        val coarseLocationGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        Log.d("BaiduLocation", "精确定位权限已授予: $fineLocationGranted, 粗略定位权限已授予: $coarseLocationGranted")
        return fineLocationGranted || coarseLocationGranted
    }

    // 请求定位权限
    private fun requestLocationPermission() {
        locationPermissionRequest.launch(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        )
    }

    /**
     * 逆地理编码，根据经纬度获取地址信息
     * @param latLng 纬度、经度
     * @param callback 回调函数，返回地址信息
     */
    private fun reverseGeoCode(latLng: LatLng, callback: (Address, String) -> Unit) {
        Log.d("BaiduGeoCode", "开始逆地理编码，纬度: ${latLng.latitude}, 经度: ${latLng.longitude}")
        val reverseGeoCodeOption = ReverseGeoCodeOption().apply {
            location(latLng)
        }
        mGeoCoder?.setOnGetGeoCodeResultListener(object : OnGetGeoCoderResultListener {
            override fun onGetReverseGeoCodeResult(result: ReverseGeoCodeResult?) {
                if (result != null) {
                    Log.d("BaiduGeoCode", "结果错误码: ${result.error}")
                    if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                        val addressComponent = result.addressDetail
                        val addressPrefix = Address(
                            province = addressComponent?.province ?: "",
                            city = addressComponent?.city ?: "",
                            district = addressComponent?.district ?: "",
                            street = addressComponent?.street ?: addressComponent?.town ?: "",
                            addressDetail = ""
                        )
                        val address = result.address
                        Log.d("BaiduGeoCode", "逆地理编码成功: $addressPrefix")
                        callback(addressPrefix, address)
                    } else {
                        Log.e("BaiduGeoCode", "逆地理编码错误: ${result.error}")
                    }
                } else {
                    Log.e("BaiduGeoCode", "逆地理编码结果为空")
                }
            }
            override fun onGetGeoCodeResult(result: GeoCodeResult?) {
                Log.d("BaiduGeoCode", "收到地理编码结果(正向): $result")
            }
        })
        mGeoCoder?.reverseGeoCode(reverseGeoCodeOption)
    }

    /**
     * BaiduMap的扩展方法
     * 设置地图中心点、缩放级别，可选动画过渡效果，用于定位后将地图聚焦到定位位置
     * @param lat 纬度
     * @param lng 经度
     * @param zoom 缩放级别
     * @param isAnimation 是否使用动画过渡效果，默认为false
     */
    private fun BaiduMap.setMapFocus(lat: Double = DEFAULTLAT, lng: Double = DEFAULTLNG, zoom: Float = DEFAULTZOOM, isAnimation: Boolean = false) {
        val center = LatLng(lat, lng)
        val mapStatus = MapStatus.Builder()
            .target(center)
            .zoom(zoom)
            .build()
        if (isAnimation) {
            this.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus))
        } else {
            this.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus))
        }
    }

    // 保存地址列表
    private fun saveUserAddressMsgs(userAddressMsgs: List<UserAddressMsg>) {
        val json = gson.toJson(userAddressMsgs)
        sharedPreferences.edit {
            putString("address_list", json)
        }
    }
    
    // 获取地址列表
    private fun getUserAddressMsgs(): List<UserAddressMsg> {
        val json = sharedPreferences.getString("address_list", null)
        return if (json != null) {
            val type = object : TypeToken<List<UserAddressMsg>>() {}.type
            gson.fromJson(json, type)
        } else {
            emptyList()
        }
    }
    
    // 添加地址
    private fun addUserAddressMsg(userAddressMsg: UserAddressMsg) {
        val addresses = getUserAddressMsgs().toMutableList()
        // 如果是默认地址，取消其他地址的默认状态
        if (userAddressMsg.isDefault) {
            addresses.forEachIndexed { index, addr ->
                addresses[index] = addr.copy(isDefault = false)
            }
        }
        addresses.add(userAddressMsg)
        saveUserAddressMsgs(addresses)
    }
    
    // 更新地址
    private fun updateUserAddressMsg(updatedUserAddressMsg: UserAddressMsg) {
        val addresses = getUserAddressMsgs().toMutableList()
        val index = addresses.indexOfFirst { it.id == updatedUserAddressMsg.id }
        if (index != -1) {
            // 如果是默认地址，取消其他地址的默认状态
            if (updatedUserAddressMsg.isDefault) {
                addresses.forEachIndexed { i, addr ->
                    addresses[i] = addr.copy(isDefault = false)
                }
            }
            addresses[index] = updatedUserAddressMsg
            saveUserAddressMsgs(addresses)
        }
    }
    
    // 删除地址
    private fun deleteAddress(addressId: String) {
        val addresses = getUserAddressMsgs().toMutableList()
        addresses.removeAll { it.id == addressId }
        saveUserAddressMsgs(addresses)
    }
    
    @Composable
    fun AddressScreen() {
        var addresses by remember { mutableStateOf(getUserAddressMsgs()) }
        var showAddDialog by remember { mutableStateOf(false) }
        var showEditDialog by remember { mutableStateOf(false) }
        var selectedUserAddressMsg by remember { mutableStateOf<UserAddressMsg?>(null) }
        var showDeleteConfirmDialog by remember { mutableStateOf(false) }
        var userAddressMsgToDelete by remember { mutableStateOf<UserAddressMsg?>(null) }
        Scaffold(
            topBar = {
                CenterAlignedTopAppBar(
                    title = { Text("地址管理") },
                    navigationIcon = {
                        IconButton(onClick = { finish() }) {
                            Icon(
                                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                contentDescription = "返回"
                            )
                        }
                    }
                )
            },
            floatingActionButton = {
                FloatingActionButton(
                    onClick = { showAddDialog = true },
                    containerColor = MaterialTheme.colorScheme.primary
                ) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "添加地址"
                    )
                }
            }
        ) { paddingValues ->
            if (addresses.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "暂无收货地址",
                        style = MaterialTheme.typography.bodyLarge
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    items(addresses) { address ->
                        AddressItem(
                            userAddressMsg = address,
                            onEdit = {
                                selectedUserAddressMsg = address
                                showEditDialog = true
                            },
                            onDelete = {
                                userAddressMsgToDelete = address
                                showDeleteConfirmDialog = true
                            },
                            onSetDefault = {
                                val updatedAddresses = addresses.map { addr ->
                                    if (addr.id == address.id) {
                                        addr.copy(isDefault = true)
                                    } else {
                                        addr.copy(isDefault = false)
                                    }
                                }
                                updatedAddresses.forEach { addr ->
                                    updateUserAddressMsg(addr)
                                }
                                addresses = getUserAddressMsgs()
                            }
                        )
                    }
                }
            }
            // 添加地址对话框
            if (showAddDialog) {
                AddressDialog(
                    onDismiss = { showAddDialog = false },
                    onConfirm = { newAddress ->
                        addUserAddressMsg(newAddress)
                        addresses = getUserAddressMsgs()
                        showAddDialog = false
                    }
                )
            }
            // 编辑地址对话框
            if (showEditDialog && selectedUserAddressMsg != null) {
                AddressDialog(
                    userAddressMsg = selectedUserAddressMsg!!,
                    onDismiss = { 
                        showEditDialog = false
                        selectedUserAddressMsg = null
                    },
                    onConfirm = { updatedAddress ->
                        updateUserAddressMsg(updatedAddress)
                        addresses = getUserAddressMsgs()
                        showEditDialog = false
                        selectedUserAddressMsg = null
                    }
                )
            }
        }
        // 删除地址确认对话框
        if (showDeleteConfirmDialog && userAddressMsgToDelete != null) {
            AlertDialog(
                onDismissRequest = {
                    showDeleteConfirmDialog = false
                    userAddressMsgToDelete = null
                },
                title = { Text("确认删除") },
                text = { Text("确定要删除地址 \"${userAddressMsgToDelete!!.name}\" 吗？") },
                confirmButton = {
                    TextButton(
                        onClick = {
                            userAddressMsgToDelete?.id?.let { deleteAddress(it) }
                            addresses = getUserAddressMsgs()
                            showDeleteConfirmDialog = false
                            userAddressMsgToDelete = null
                        }
                    ) { Text("确定") }
                },
                dismissButton = {
                    TextButton(
                        onClick = {
                            showDeleteConfirmDialog = false
                            userAddressMsgToDelete = null
                        }
                    ) { Text("取消") }
                }
            )
        }
    }
    
    @Composable
    fun AddressItem(
        userAddressMsg: UserAddressMsg,
        onEdit: () -> Unit,
        onDelete: () -> Unit,
        onSetDefault: () -> Unit
    ) {
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.cardElevation(
                defaultElevation = 2.dp
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                // 联系人信息
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = userAddressMsg.name,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold
                    )
                    if (userAddressMsg.isDefault) {
                        Text(
                            text = "默认",
                            color = MaterialTheme.colorScheme.primary,
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                }
                // 电话
                Text(
                    text = userAddressMsg.phone,
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(top = 4.dp)
                )
                // 地址
                Text(
                    text = "${userAddressMsg.address.province}${userAddressMsg.address.city}${userAddressMsg.address.district}${userAddressMsg.address.street}${userAddressMsg.address.addressDetail}",
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(top = 4.dp)
                )
                // 操作按钮
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 12.dp),
                    horizontalArrangement = Arrangement.End
                ) {
                    if (!userAddressMsg.isDefault) {
                        TextButton(
                            onClick = onSetDefault
                        ) {
                            Text("设为默认")
                        }
                    }
                    TextButton(
                        onClick = onEdit
                    ) {
                        Text("编辑")
                    }
                    TextButton(
                        onClick = onDelete
                    ) {
                        Text("删除")
                    }
                }
            }
        }
    }

    @Composable
    fun AddressDialog(
        userAddressMsg: UserAddressMsg? = null,
        onDismiss: () -> Unit,
        onConfirm: (UserAddressMsg) -> Unit
    ) {
        val coroutineScope = rememberCoroutineScope()
        // 输入框文本变量
        var name by remember { mutableStateOf(userAddressMsg?.name ?: "") }
        var phone by remember { mutableStateOf(userAddressMsg?.phone ?: "") }
        var province by remember { mutableStateOf(userAddressMsg?.address?.province ?: "") }
        var city by remember { mutableStateOf(userAddressMsg?.address?.city ?: "") }
        var district by remember { mutableStateOf(userAddressMsg?.address?.district ?: "") }
        var street by remember { mutableStateOf(userAddressMsg?.address?.street ?: "") }
        var addressDetail by remember { mutableStateOf(userAddressMsg?.address?.addressDetail ?: "") }
        // 状态变量
        var isDefault by remember { mutableStateOf(userAddressMsg?.isDefault ?: false) }
        var showMapSelector by remember { mutableStateOf(false) }
        if (showMapSelector) {
            // 显示地图选点界面
            MapSelectorDialog(
                onLocationSelected = { lat, lng ->
                    // 根据经纬度获取地址信息
                    val latLng = LatLng(lat, lng)
                    context.reverseGeoCode(latLng) { addressInfo, address ->
                        province = addressInfo.province
                        city = addressInfo.city
                        district = addressInfo.district
                        street = addressInfo.street
                    }
                    showMapSelector = false
                },
                onDismiss = { showMapSelector = false }
            )
        }
        AlertDialog(
            onDismissRequest = onDismiss,
            title = { Text(if (userAddressMsg == null) "添加地址" else "编辑地址") },
            text = {
                val scrollState = rememberScrollState()
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .verticalScroll(scrollState),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedTextField(
                        value = name,
                        onValueChange = { name = it },
                        label = { Text("收货人") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    OutlinedTextField(
                        value = phone,
                        onValueChange = { phone = it },
                        label = { Text("手机号码") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    // 定位和地图选点按钮
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "地址信息",
                            style = MaterialTheme.typography.bodyMedium
                        )
                        Row {
                            IconButton(onClick = {
                                // 自动填写输入框
                                context.location {
                                    coroutineScope.launch {
                                        province = context.currentProvince
                                        city = context.currentCity
                                        district = context.currentDistrict
                                        street = context.currentStreet
                                        showMapSelector = false
                                    }
                                }
                            }) {
                                Icon(
                                    imageVector = Icons.Default.LocationOn,
                                    contentDescription = "定位"
                                )
                            }
                            IconButton(onClick = {
                                context.location {
                                    coroutineScope.launch {
                                        showMapSelector = true
                                    }
                                }
                            }) {
                                Icon(
                                    imageVector = Icons.Default.Search,
                                    contentDescription = "地图选点"
                                )
                            }
                        }
                    }
                    OutlinedTextField(
                        value = province,
                        onValueChange = { province = it },
                        label = { Text("省/自治区/直辖市") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    OutlinedTextField(
                        value = city,
                        onValueChange = { city = it },
                        label = { Text("市") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    OutlinedTextField(
                        value = district,
                        onValueChange = { district = it },
                        label = { Text("区/县") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    OutlinedTextField(
                        value = street,
                        onValueChange = { street = it },
                        label = { Text("街道") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    OutlinedTextField(
                        value = addressDetail,
                        onValueChange = { addressDetail = it },
                        label = { Text("详细地址") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Checkbox(
                            checked = isDefault,
                            onCheckedChange = { isDefault = it }
                        )
                        Text(
                            text = "设为默认地址",
                            modifier = Modifier.clickable { isDefault = !isDefault }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        val fullAddress = "$province$city$district$street$addressDetail"
                        if (name.isNotBlank() && phone.isNotBlank() && fullAddress.isNotBlank()) {
                            val newUserAddressMsg = UserAddressMsg(
                                id = userAddressMsg?.id ?: UUID.randomUUID().toString(),
                                name = name,
                                phone = phone,
                                address = Address(
                                    province = province,
                                    city = city,
                                    district = district,
                                    street = street,
                                    addressDetail = addressDetail
                                ),
                                isDefault = isDefault
                            )
                            onConfirm(newUserAddressMsg)
                        }
                    },
                    enabled = name.isNotBlank() && phone.isNotBlank() &&
                            province.isNotBlank() && city.isNotBlank() && district.isNotBlank() && street.isNotBlank() && addressDetail.isNotBlank()
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(onClick = onDismiss) {
                    Text("取消")
                }
            }
        )
    }

    // 地图选点对话框
    @Composable
    fun MapSelectorDialog(
        initialLat: Double? = null,
        initialLng: Double? = null,
        onLocationSelected: (Double, Double) -> Unit,
        onDismiss: () -> Unit
    ) {
        val scope = rememberCoroutineScope()
        var selectedLat by remember { mutableDoubleStateOf(initialLat ?: currentLatitude) }
        var selectedLng by remember { mutableDoubleStateOf(initialLng ?: currentLongitude) }
        var isMapInitialized by remember { mutableStateOf(false) }
        var mapViewRef by remember { mutableStateOf<MapView?>(null) }
        var addressStr by remember { mutableStateOf("") }
        LaunchedEffect(selectedLat, selectedLng) {
            context.reverseGeoCode(LatLng(selectedLat, selectedLng)) { _, address ->
                addressStr = address
            }
        }
        AlertDialog(
            onDismissRequest = onDismiss,
            title = {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text("地图选点")
                    IconButton(
                        onClick = {
                            context.location {
                                scope.launch {
                                    // 改变焦点
                                    mapViewRef?.map?.setMapFocus(currentLatitude, currentLongitude)
                                    // 更新位置
                                    selectedLat = currentLatitude
                                    selectedLng = currentLongitude
                                    // 添加标记
                                    val latLng = LatLng(currentLatitude, currentLongitude)
                                    mapViewRef?.map?.clear()
                                    val markerOptions = MarkerOptions()
                                        .position(latLng)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mark))
                                        .animateType(MarkerOptions.MarkerAnimateType.jump)
                                    mapViewRef?.map?.addOverlay(markerOptions)
                                }
                            }
                        }
                    ) {
                        Icon(
                            imageVector = Icons.Default.LocationOn,
                            contentDescription = "定位到当前位置"
                        )
                    }
                }
            },
            text = {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(400.dp)
                ) {
                    Text(
                        text = "请选择您的位置: \n${addressStr}",
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(bottom = 8.dp)
                    )
                    // 使用 AndroidView 集成百度地图
                    AndroidView(
                        factory = {
                            // 创建 MapView 实例
                            val mapView = MapView(context)
                            mapViewRef = mapView
                            val baiduMap = mapView.map
                            // 设置地图属性
                            baiduMap.mapType = BaiduMap.MAP_TYPE_NORMAL
                            baiduMap.uiSettings.isRotateGesturesEnabled = true
                            baiduMap.uiSettings.isOverlookingGesturesEnabled = true
                            // 地图点击监听器
                            baiduMap.setOnMapClickListener(object : BaiduMap.OnMapClickListener {
                                override fun onMapClick(latLng: LatLng?) {
                                    latLng?.let {
                                        selectedLat = it.latitude
                                        selectedLng = it.longitude
                                        // 清除之前的标记
                                        baiduMap.clear()
                                        // 添加新标记
                                        val markerOptions = MarkerOptions()
                                            .position(it)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mark))
                                            .animateType(MarkerOptions.MarkerAnimateType.jump)
                                        baiduMap.addOverlay(markerOptions)
                                    }
                                }
                                override fun onMapPoiClick(poi: MapPoi?) {
                                    poi?.position?.let {
                                        selectedLat = it.latitude
                                        selectedLng = it.longitude
                                        // 清除之前的标记
                                        baiduMap.clear()
                                        // 添加新标记
                                        val markerOptions = MarkerOptions()
                                            .position(it)
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_mark))
                                            .animateType(MarkerOptions.MarkerAnimateType.jump)
                                        baiduMap.addOverlay(markerOptions)
                                    }
                                }
                            })
                            // 设置初始焦点（当前位置）和缩放级别
                            baiduMap.setMapFocus(currentLatitude, currentLongitude)
                            isMapInitialized = true
                            mapView
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                    )
                }
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        onLocationSelected(selectedLat, selectedLng)
                        onDismiss()
                    },
                    enabled = isMapInitialized
                ) {
                    Text("确认选点")
                }
            },
            dismissButton = {
                TextButton(onClick = onDismiss) {
                    Text("取消")
                }
            }
        )
    }
}